package com.ler.yrmall.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ler.yrmall.basic.Form;
import com.ler.yrmall.basic.Result;
import com.ler.yrmall.coupon.entity.SeckillSkuRelationEntity;
import com.ler.yrmall.coupon.mapper.SeckillSkuRelationMapper;
import com.ler.yrmall.coupon.service.SeckillSkuRelationService;
import com.ler.yrmall.coupon.vo.SeckillSkuRelationVO;
import com.ler.yrmall.enums.ErrorCodeEnum;
import com.ler.yrmall.exception.BusinessException;
import com.ler.yrmall.product.api.ProductApi;
import com.ler.yrmall.product.dto.SkuDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author leron
 */
@Service
public class SeckillSkuRelationServiceImpl extends ServiceImpl<SeckillSkuRelationMapper, SeckillSkuRelationEntity> implements SeckillSkuRelationService {

    @DubboReference
    private ProductApi productApi;

    @Override
    public IPage<SeckillSkuRelationVO> find(Form request) {
        IPage<SeckillSkuRelationEntity> page = this.page(request.getPage(), Wrappers.<SeckillSkuRelationEntity>lambdaQuery().orderByAsc(SeckillSkuRelationEntity::getSort));
        List<Long> skuIds = page.getRecords().stream().map(SeckillSkuRelationEntity::getSkuId).collect(Collectors.toList());
        if (!skuIds.isEmpty()) {
            Result<List<SkuDTO>> skuResponse = productApi.listSkuByIds(skuIds);
            Assert.isTrue(skuResponse.isSuccess(),() -> new BusinessException(ErrorCodeEnum.SKU_FIND_ERROR));
            Map<Long, SkuDTO> skuMap = skuResponse.getData().stream().collect(Collectors.toMap(SkuDTO::getId, Function.identity(), (a, b) -> a));
            return page.convert(item -> {
                SeckillSkuRelationVO vo = BeanUtil.copyProperties(item, SeckillSkuRelationVO.class);
                vo.setSkuName(Optional.ofNullable(skuMap.get(item.getSkuId())).map(SkuDTO::getName).orElse(""));
                return vo;
            });
        }
        return page.convert(e -> BeanUtil.copyProperties(e,SeckillSkuRelationVO.class));
    }

}